<template>
  <a-col :span="12" h-full ref="el">
    <a-space mb-4>
      <a-button type="primary" @click="addNewCondition">新建条件</a-button>
      <a-button
        type="primary"
        @click="batchRemove"
        :disabled="!selectedRowKeys.length"
      >
        批量删除
      </a-button>
    </a-space>
    <a-table
      bordered
      size="small"
      :columns="columns"
      :data-source="tableCollection.tableData"
      :pagination="false"
      :scroll="{ y: rowH - 88 }"
      :row-selection="{
        selectedRowKeys,
        onChange: selectChange,
      }"
      :row-key="genRowKey"
      :custom-row="customActiveRow"
    ></a-table>
    <a-modal
      v-model:open="open"
      title="条件组合"
      width="800px"
      destroy-on-close
      :maskClosable="false"
    >
      <condition-combination
        :condition="condition"
        ref="conditionRef"
      ></condition-combination>
      <template #footer>
        <a-space>
          <a-button @click="reset">重置</a-button>
          <a-button @click="open = false">取消</a-button>
          <a-button type="primary" @click="confirm">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </a-col>
</template>

<script lang="tsx" setup>
import { TableColumnType } from 'ant-design-vue';
import {
  EditOutlined,
  SettingOutlined,
  SettingFilled,
} from '@ant-design/icons-vue';
import { Condition, Match, TableRow } from '../type';
import ConditionTable from './conditionTable';
import ConditionCombination from './ConditionCombination.vue';
import { Logic } from './Pick';
import { event } from './event';

const props = defineProps<{
  tableCollection: ConditionTable;
  rowH: number;
}>();

const { tableCollection } = toRefs(props);
const open = ref(false);
const condition = ref({} as Condition);
const getCondition = condition_name => {
  const { conditionMap } = tableCollection.value.getMap;
  return conditionMap.get(condition_name);
};
const isConfig = conditionName => {
  const condition = getCondition(conditionName);
  if (condition?.match_rule?.logic_type == 'and') return true;
  if (condition?.match_rule?.children?.length) {
    return condition.match_rule.children.some(item => item.type == 'complex');
  }
  return false;
};
const columns: TableColumnType[] = [
  {
    title: '条件',
    customCell: data => {
      return {
        rowSpan: data.rowSpan,
      };
    },
    customRender({ record }) {
      if (record.isEdit) {
        return (
          <a-input
            ref={inputRef}
            v-model:value={[tempInputData.value, ['trim']]}
            maxlength={20}
            onBlur={() => {
              tableCollection.value.save(tempInputData.value, record, inputRef);
            }}
            onPressEnter={() => {
              inputRef.value?.blur();
            }}
          ></a-input>
        );
      } else {
        return (
          <div>
            {record.alias_name || record.condition_name}
            <a-button
              type="link"
              icon={h(EditOutlined)}
              onClick={() => {
                tempInputData.value =
                  record.alias_name || record.condition_name;
                tableCollection.value.modify(record, inputRef);
              }}
            ></a-button>
            {(getCondition(record.alias_name)?.matches.length || 0) > 1 && (
              <a-button
                type="link"
                icon={
                  isConfig(record.alias_name) ? (
                    <SettingFilled />
                  ) : (
                    <SettingOutlined />
                  )
                }
                onClick={() => {
                  condition.value = getCondition(record.alias_name)!;
                  open.value = true;
                }}
              ></a-button>
            )}
          </div>
        );
      }
    },
    width: '200px',
  },
  {
    title: '匹配站点条件',
    ellipsis: true,
    customRender({ record }) {
      const { website_code, category_name, condition_name } = (
        record as TableRow
      ).website;
      if (website_code && category_name && condition_name)
        return `${website_code}-${category_name}:${condition_name}`;
    },
  },
  {
    title: '站点条件选项',
    dataIndex: 'website',
    ellipsis: true,
    customRender({ value }) {
      return value.options.map(item => item.option_name).join(',');
    },
  },
  {
    title: '操作',
    customRender({ record }) {
      return (
        <a-button
          type="link"
          disabled={record.isEdit}
          onClick={() => {
            props.tableCollection.remove(record);
            const condition = getCondition((record as TableRow).condition_name);
            const remove = (list: Logic<{ condition_id: string }>[]) => {
              const idx = list.findIndex(item => {
                const { website } = record as TableRow;
                const { website_code, category_code, condition_name } = website;
                if (item.children) {
                  remove(item.children);
                }
                return (
                  item.condition_id ==
                  `${website_code}:${category_code}:${condition_name}`
                );
              });
              if (idx > -1) {
                list.splice(idx, 1);
              }
            };
            if (condition?.match_rule?.children) {
              remove(condition.match_rule.children);
            }
            event.emit('change');
          }}
        >
          删除
        </a-button>
      );
    },
    width: 80,
  },
];

const inputRef = ref<HTMLInputElement>();
const tempInputData = ref('');

const addNewCondition = () => {
  tempInputData.value = '';
  tableCollection.value.addNew(inputRef);
};

const conditionRef = ref<InstanceType<typeof ConditionCombination>>();
const confirm = () => {
  if (conditionRef.value) {
    conditionRef.value
      .validate()
      .then(() => {
        open.value = false;
        event.emit('modify');
      })
      .catch(err => {
        message.error(err);
      });
  }
};
const reset = () => {
  if (conditionRef.value) {
    conditionRef.value.reset();
  }
};

const selectedRowKeys = ref<string[]>([]);
const selectedRows = ref<TableRow[]>([]);
const selectChange = (keys, rows) => {
  selectedRowKeys.value = keys;
  selectedRows.value = rows;
};

const genRowKey = item => {
  const { condition_name, website } = item as TableRow;
  const {
    category_code,
    category_name,
    category_path,
    condition_name: cname,
  } = website;
  return `${condition_name}-${website.condition_name}-${category_code}-${category_name}-${category_path}-${cname}`;
};

const batchRemove = () => {
  selectedRows.value.forEach(item => {
    tableCollection.value.remove(item);
  });
  selectedRowKeys.value = [];
  selectedRows.value = [];
};

const customActiveRow = (record: TableRow) => {
  if (
    activeRow.value &&
    compare(record.website, activeRow.value, [
      'category_code',
      'category_name',
      'website_code',
      'condition_name',
    ])
  ) {
    nextTick(() => {
      const el = document.querySelector(
        `tr[data-row-key='${genRowKey(record)}']`
      );
      el?.scrollIntoView({ behavior: 'smooth' });
    });
    return {
      class: 'row-active',
    };
  }
  return {};
};

const rowMap = ref<Map<string, Match>>(new Map());
const activeKey = ref('');
const activeRow = computed(() => rowMap.value.get(activeKey.value));
onMounted(() => {
  event.on('changeKey', key => {
    activeKey.value = key as string;
  });
  event.on('changeRow', value => {
    const { website_code, row } = value as any;
    rowMap.value.set(website_code, row);
  });
});
</script>
